package org.creavi.engine.texture;

import java.net.URL;
import java.util.HashMap;

import org.creavi.engine.resource.ResourceLocator;

import com.jme.image.Texture;
import com.jme.scene.state.TextureState;
import com.jme.system.DisplaySystem;
import com.jme.util.TextureManager;

public class TextureFactory {
	private static TextureFactory textureFactory;

	public synchronized static TextureFactory getInstance() {
		if (textureFactory == null) {
			textureFactory = new TextureFactory();
		}

		return textureFactory;
	}

	private HashMap<String, Texture> cache;

	private TextureFactory() {
		cache = new HashMap<String, Texture>();
	}

	private Texture loadTextureFromDisk(String name) {
		Texture texture = null;
		URL url = ResourceLocator.locatePngTexture(name);
		
		texture = TextureManager.loadTexture(url);

		return texture;
	}

	public Texture loadTexture(String name) {
		Texture texture = null;

		if (cache.containsKey(name)) {
			texture = cache.get(name);
		} else {
			texture = loadTextureFromDisk(name);

			cache.put(name, texture);
		}

		return texture.createSimpleClone();
	}

	public TextureState createTextureState(String name) {
		TextureState ts = DisplaySystem.getDisplaySystem().getRenderer()
				.createTextureState();
		ts.setEnabled(true);
		Texture textura = loadTexture(name);
		ts.setTexture(textura);

		return ts;
	}
}
